<template>
  <div class="dashboard-container">
    <dv-full-screen-container>
      <!-- 顶部标题栏 -->
      <div class="header">
        <div class="nav-buttons">
          <div class="monitor">全屏监控</div>
          <button 
            type="button"
            class="fetch-btn" 
            @click="handleFetchData"
            :disabled="loading"
            @mousedown="console.log('按钮被点击')"
          >
            {{ loading ? '正在获取数据...' : '获取最新数据' }}
          </button>
        </div>
        <div class="title">智慧农产品数字化实时追溯系统</div>
        <div class="time">{{ currentTime }}</div>
      </div>

      <!-- 主体内容 -->
      <div class="main-content">
        <LeftPanel />
        <CenterPanel />
        <RightPanel />
      </div>
    </dv-full-screen-container>
  </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount, provide, watch } from 'vue'
import { useRouter } from 'vue-router'
import { post, get } from '@/utils/request'
import LeftPanel from './dashboard/LeftPanel.vue'
import CenterPanel from './dashboard/CenterPanel.vue'
import RightPanel from './dashboard/RightPanel.vue'
import { ElMessage } from 'element-plus'
import 'element-plus/dist/index.css'

const router = useRouter()

// 当前时间
const currentTime = ref('')
let timer = null

// 加载状态
const loading = ref(false)
watch(loading, (newVal) => {
  console.log('loading 状态变化:', newVal)
})

// 存储获取到的土壤数据
const soilData = ref({})

// 提供一个加载状态控制
provide('dataLoadingReady', true)

// 更新时间
const updateTime = () => {
  const now = new Date()
  currentTime.value = now.toLocaleString()
}

// 修改获取数据的方法
const handleFetchData = async () => {
  console.log('handleFetchData 被触发')
  loading.value = true
  
  try {
    // 发送 POST 请求到所有传感器接口
    const fetchPromises = [
      post('/soil/ph/fetch'),
      post('/soil/nitrogen/fetch'),
      post('/soil/phosphorus/fetch'),
      post('/soil/potassium/fetch'),
      post('/ah/fetch'),
      post('/at/fetch'),
      post('/st/fetch'),
    ]
    
    // 等待所有 POST 请求完成并获取结果
    const results = await Promise.all(fetchPromises)
    
    // 检查是否所有传感器都返回了成功消息
    const allSuccess = results.every(result => 
      typeof result === 'string' && result.includes('成功获取并存储')
    )
    
    if (allSuccess) {
      ElMessage.success('所有数据更新成功！')
    } else {
      console.error('部分传感器请求失败，详细结果:', results)
      ElMessage.error('部分传感器数据获取失败')
    }
  } catch (error) {
    console.error('获取数据出错:', error)
    ElMessage.error('获取数据出错')
  } finally {
    loading.value = false
  }
}

onMounted(() => {
  console.log('组件已挂载')
  updateTime()
  timer = setInterval(updateTime, 1000)
  const token = localStorage.getItem('token')
  console.log('当前 token:', token)
  if (!token) {
    console.log('未找到 token，跳转到登录页')
    router.push('/login')
    return
  }
})

onBeforeUnmount(() => {
  clearInterval(timer)
})
</script>

<style lang="scss" scoped>
.dashboard-container {
  width: 100%;
  height: 100vh;
  color: #fff;
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;

  :deep(.dv-full-screen-container) {
    width: 100% !important;
    height: 100% !important;
    overflow: hidden !important;
  }

  .header {
    height: 50px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 0 20px;
    background: linear-gradient(to right, rgba(3, 211, 236, 0.1), rgba(3, 211, 236, 0.2));

    .nav-buttons {
      display: flex;
      align-items: center;
      gap: 20px;

      .monitor {
        background: rgba(3, 211, 236, 0.2);
        border: 1px solid #03d3ec;
        color: #fff;
        padding: 5px 15px;
        border-radius: 4px;
      }

      .fetch-btn {
        background: transparent;
        border: 1px solid #03d3ec;
        color: #fff;
        padding: 5px 15px;
        border-radius: 4px;
        cursor: pointer;
        transition: all 0.3s ease;

        &:hover {
          background: rgba(3, 211, 236, 0.1);
        }

        &:disabled {
          opacity: 0.6;
          cursor: not-allowed;
        }

        &:active {
          transform: scale(0.98);
        }
      }
    }

    .title {
      font-size: 24px;
      font-weight: bold;
    }

    .time {
      font-size: 16px;
    }
  }

  .main-content {
    display: flex;
    height: calc(100vh - 50px);
    padding: 5px 10px;
    gap: 10px;
    overflow: hidden;
  }
}
</style>